const ylTenureTree = {
  template: `<ul>
    <li :class="isfirst?'part-diagram_root':''" v-for="(item,index) in data" :key="index">
        <div class="picture">
            <div class="child_picture">
                <img :src="item.Picture_URL?photo + item.Picture_URL:'../../admin/icons/NoLogo.png'">
            </div>
        </div>
        <div class="bkuang">
            <span class="subtitle">{{item.Party_Position}}</span>
            <br>
            <span class="nametitle">{{item.Personal_Name}}</span>
            <br>
            <!--<el-button :type="item.Party_Member_SerialNumber?'danger':'primary'" @click="handle(item)">
                {{item.Party_Member_SerialNumber?'离任':'补选'}}
            </el-button>-->
        </div>
        <yl-tenure-tree v-if="item.children.length > 0" @node-click="handle" :data="item.children"></yl-tenure-tree>
    </li></ul>`,
  props: {
    data: {
      type: Array,
      default: function () {
        return [];
      },
    },
    isfirst: {
      type: Boolean,
      default: false,
    },
  },
  emits: ["node-click"],
  data() {
    return {
      photo,
    };
  },
  methods: {
    handle(item) {
      this.$emit("node-click", item);
    },
  },
};
const App = {
  mixins: [Query], //配置文件，路径/utils/mixins.js
  data() {
    return {
      treeData1: [],
      nowVal: 100,
      currentPage: 1, //当前页码
      pageSize: 10, // 每页记录数
      total: "",
      activeName: "first",
      teeed: "", //用于存储点击树节点获取的党组织编号
      type: "",
      currentNode: null, // 用于存储当前点击的节点数据
      party_organization: {
        Party_Organization_Name: "", //党组织名称
        Establishment_Date: "", //成立日期
        Parent_Serialnumber: "", //上级组织编号
        Party_Organization_Type: "", //组织类型
        Party_Organization_Level: "", //党组级别 只有党委选择
        Party_Organization_Address: "", //党组地址
        Party_Organization_Coords: "", //党组所在地坐标集
        Party_Organization_Captain_Number: "", //党组负责人编号
        Enterprise_SeriralNumber: "", //党组所在企业编号
      },
      hide: "",
      dialogVisible: false,
      loading1: false,
      totalMembers: 111, //总人数
      fullMembers: 11, //正式党员
      probationaryMembers: 1, //预备党员
      input: "", //输入框
      options: [
        //下拉菜单
        {
          value: "群众",
          label: "群众",
        },
        {
          value: "无党派人士",
          label: "无党派人士",
        },
        {
          value: "民主党派成员",
          label: "民主党派成员",
        },
        {
          value: "共青团员",
          label: "共青团员",
        },
        {
          value: "中共预备党员",
          label: "中共预备党员",
        },
        {
          value: "中共党员",
          label: "中共党员",
        },
      ],
      zuzhitype: [
        {
          value: "党委",
          label: "党委",
        },
        {
          value: "总支",
          label: "总支",
        },
        {
          value: "支部",
          label: "支部",
        },
      ],
      treeData: [], //树的数据
      originalTreeData: [], //原始树的数据
      originalTableData: [], // 原始表格的数据
      columns: [], //表格的列
      loading: false, //表数据的懒加载
      showDialog: false, //设置字段弹窗
      checkedFields: [], //选中的字段
      isDataReady: false,
      Tabletdata: [], //表格的数据
      fields: [], //字段列表
      // showaddDialog: false, //添加字段弹窗
      value: "",
      page: {
        PageNumber: 1, //页码
        RowAmount: 20,
        Condition: window.btoa(unescape(encodeURIComponent("%%"))),
      },
      nodeName: ''
    };
  },
  mounted() {
    this.Treedata();
    // this.getList();
    // this.getList1();
  },
  computed: {
    // 计算属性，返回选中的字段
    isAllChecked() {
      return this.checkedFields.length === this.fields.length;
    },
  },

  methods: {
    // 导出方法
    Batchexport() {
      const that = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryBySQLSerialNumber`,
        method: "post",
        data: {
          SQLSerialNumber: "s_base_sql_table_config",
          Condition: window.btoa(
            unescape(encodeURIComponent("%" + this.relativePath + "%"))
          ),
          ExtensionCondition: "",
        },
        success: (columns) => {
          console.log(columns);
          $.ajax({
            headers: requestHeaders(),
            method: "post",
            url: mh + "/generalBusiness/generalQueryBySQLSerialNumber",
            data: {
              Model_Url: this.relativePath,
              Condition: this.page.Condition,
              ExtensionCondition: this.page.ExtensionCondition || "",
            },
            success: (data) => {
              if (data.length > 0) {
                this.$confirm(
                  `当前共查出${data.length}条数据, 是否继续?`,
                  "提示",
                  {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "success",
                  }
                )
                  .then(() => {
                    console.log("点击了确认");

                    this.$prompt("请输入您导出的文件名", "提示", {
                      confirmButtonText: "确定",
                      cancelButtonText: "取消",
                    })
                      .then(({ value }) => {
                        this.$message({
                          type: "success",
                          message: "你的文件名是: " + value,
                        });
                        if (!value) {
                          value = "未知名";
                        }
                        // return;
                        const wb = XLSX.utils.book_new();
                        const ws_data = [columns.map((i) => i.COLUMN_COMMENT)];
                        const ws_main = data.map((item) =>
                          columns.map((row) => item[row.COLUMN_NAME])
                        );
                        const ws = XLSX.utils.aoa_to_sheet([
                          ...ws_data,
                          ...ws_main,
                        ]);
                        ws["!cols"] = [];
                        for (
                          let i = 0;
                          i < Object.keys(ws_data[0]).length;
                          i++
                        ) {
                          ws["!cols"].push({ wpx: 150 });
                        }
                        XLSX.utils.book_append_sheet(wb, ws, value);
                        XLSX.writeFile(wb, value + ".xlsx");
                      })
                      .catch((error) => {
                        console.error(error);
                        // this.$message({
                        //   type: "info",
                        //   message: "取消输入",
                        // });
                      });
                  })
                  .catch((erro) => {
                    console.log(erro);
                  });
              } else {
                this.$message({
                  message: "未查询出可导出的数据!",
                  type: "warning",
                });
              }
            },
            complete: (XMLHttpRequest) => {
              requestPretreatment(XMLHttpRequest);
            },
          });
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
      });
    },
    // 导入数据方法
    import_data() {
      window.location.href = "./import.html";
    },
    zoomSize(type) {
      if (type == 1) {
        if (this.nowVal == 50) return;
        this.nowVal -= 10;
      } else {
        if (this.nowVal == 300) return;
        this.nowVal += 10;
      }
    },
    handleNode(node) {
      if (node.Party_Member_SerialNumber) {
        //离任
        this.form = {
          Tenure_SerialNumber: node.Tenure_SerialNumber,
          Tenure_Position_SerialNumber: node.Tenure_Position_SerialNumber,
          Party_Member_SerialNumber: node.Party_Member_SerialNumber,
          Party_Position_SerialNumber: node.Party_Position_SerialNumber,
          Actual_End_Date: "",
          Leave_Type: "",
          Tenure_Status: "3",
          Picture_URL: node.Picture_URL,
          Children: {
            party_organization_tenure_attachment: [],
          },
        };
      } else {
        //补选
        this.form = {
          Tenure_SerialNumber: node.Tenure_SerialNumber,
          Tenure_Position_SerialNumber: node.Tenure_Position_SerialNumber,
          Party_Member_SerialNumber: "",
          Party_Position_SerialNumber: node.Party_Position_SerialNumber,
          Accession_Date: "",
          Election_Date: "",
          Tenure_Status: "1",
          Picture_URL: "",
          Children: {
            party_organization_tenure_attachment: [],
          },
        };
      }
      this.showDialog = true;
    },
    handleNodeClick(data, node) {
      this.nodeKey = data.Party_Organization_SerialNumber;
      this.nodeName = data.Party_Organization_Name;
      let arr = [];
      if (data.children) {
        this.Organization(data.children, arr);
      }
      let str = "";
      [data.Party_Organization_SerialNumber, ...arr].forEach((item) => {
        if (str) {
          str += "\r\nOR party_member_information.Party_Organization_SerialNumber='" + item + "'";
        } else {
          str = "\r\nparty_member_information.Party_Organization_SerialNumber='" + item + "'";
        }
      });
      if (str) {
        str = "AND (" + str + ")";
      }
      this.page.ExtensionCondition = window.btoa(
        unescape(encodeURIComponent(str))
      );
      // 调用获取表格数据的方法，并传入党组织编号作为过滤条件
      this.postgetList(this.page);
      this.loading1 = true;
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryByTableName`,
        type: "post",
        data: {
          Data: 'party_organization_tenure',
          Condition: `Party_Organization_SerialNumber = '${this.nodeKey}'
          AND DATE(NOW()) BETWEEN Start_Date AND End_Date
          AND Row_Status = '0'
          ORDER BY Create_Datetime DESC
          LIMIT 1`,
        },
        success: (data) => {
          if (data.length > 0) {
            $.ajax({
              headers: requestHeaders(),
              url: `${mh}/generalBusiness/getPartyOrganizationPositionTreeByTenure`,
              type: "GET",
              data: {
                Tenure_SerialNumber: data[0].Tenure_SerialNumber
              },
              success: (data) => {
                console.log(data);
                this.treeData1 = data;
              },
              complete: (XMLHttpRequest) => {
                requestPretreatment(XMLHttpRequest);
                this.loading1 = false;
              },
              dataType: "json",
            });
          } else {
            this.loading1 = false;
          }
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
    handlePlaceFile(data) {
      this.$confirm('将该数据进行归档,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        let { TableName, primary_key } = JSON.parse(document.getElementById("table").getAttribute("data-options"));
        $.ajax({
          headers: requestHeaders(),
          url: `${mh}/generalBusiness/queryMultiTableByCondition`,
          method: "post",
          data: {//查询未归档的数据
            Data: JSON.stringify([{
              tableName: 'party_member_information',
              Condition: window.btoa(unescape(encodeURIComponent(primary_key + "='" + data[primary_key] + "' AND Place_File = '0'"))),
            }, {
              tableName: 'party_member_event',
              Condition: window.btoa(unescape(encodeURIComponent(primary_key + "='" + data[primary_key] + "' AND Place_File = '0' AND Row_Status = '0'"))),
            }, {
              tableName: 'party_member_attachment',
              Condition: window.btoa(unescape(encodeURIComponent(primary_key + "='" + data[primary_key] + "' AND Place_File = '0' AND Row_Status = '0'"))),
            }]),
          },
          success: ({ party_member_information, party_member_event, party_member_attachment }) => {
            if (party_member_information.length > 0 || party_member_event.length > 0 || party_member_attachment.length > 0) {
              party_member_information.forEach(item => {
                item.Place_File = '1';
              })
              party_member_event.forEach(item => {
                item.Place_File = '1';
              })
              party_member_attachment.forEach(item => {
                item.Place_File = '1';
              })

              let lJSONObject_DataSet = {
                Modify: {
                  party_member_information, party_member_event, party_member_attachment
                }
              };

              let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
              lJSONObject_DataSet['Add'] = new Object();
              lJSONObject_DataSet['Add']['base_operation_log'] = [{
                Operation_Type: '0',
                Operation_Path: this.relativePath,
                Operation_Main,
                Operation_Interface: "generalSaveByRequestBody",
                Operation_IP: getIpAddress()
              }]
              submitSave(lJSONObject_DataSet, (res) => {
                if (res.Status == 'success') {
                  this.postgetList(this.page);
                  this.$message({
                    type: 'success',
                    message: '操作成功'
                  });
                } else {
                  this.$message({
                    type: 'error',
                    message: '操作失败'
                  });
                }
              })
            } else {
              this.$message({
                type: 'error',
                message: '暂无需归档的数据'
              });
            }
          },
          complete: (XMLHttpRequest) => {
            requestPretreatment(XMLHttpRequest);
          },
        });
      }).catch(() => { });
    },
    Organization(data, arr) {
      data.forEach((item) => {
        arr.push(item.Party_Organization_SerialNumber);
        if (item.children && item.children.length > 0) {
          this.Organization(item.children, arr);
        }
      });
    },
    check() {
      console.log(this.input);
      if (this.input) {
        this.page.Condition = window.btoa(unescape(encodeURIComponent("%" + this.input + "%")));
      } else {
        this.page.Condition = window.btoa(
          unescape(encodeURIComponent("%%"))
        );
      }
      this.postgetList(this.page);
    },
    handleClick(tab, event) {
      console.log(tab);
      // 标签点击方法
      if (tab.props.name === "second") {
        this.loading1 = true;
        $.ajax({
          headers: requestHeaders(),
          url: `${mh}/generalBusiness/generalQueryByTableName`,
          type: "post",
          data: {
            Data: 'party_organization_tenure',
            Condition: `Party_Organization_SerialNumber = '${this.nodeKey}'
            AND DATE(NOW()) BETWEEN Start_Date AND End_Date
            AND Row_Status = '0'
            ORDER BY Create_Datetime DESC
            LIMIT 1`,
          },
          success: (data) => {
            if (data.length > 0) {
              $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/getPartyOrganizationPositionTreeByTenure`,
                type: "GET",
                data: {
                  Tenure_SerialNumber: data[0].Tenure_SerialNumber
                },
                success: (data) => {
                  console.log(data);
                  this.treeData1 = data;
                },
                complete: (XMLHttpRequest) => {
                  this.loading1 = false;
                  requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
              });
            } else if (this.nodeKey) {
              this.treeData1 = []
              this.$message({
                message: '当前党组未查询到当前任期党员结构',
                type: 'warning'
              });
              this.loading1 = false;
            } else {
              this.loading1 = false;
            }
          },
          complete: (XMLHttpRequest) => {
            requestPretreatment(XMLHttpRequest);
          },
          dataType: "json",
        });
      }
    },
    personalAdd() {
      window.location.href = "./party_member_informationAdd.html?action=Add";
    },
    //编辑按钮
    handleEdit(row) {
      let { primary_key } = JSON.parse(
        document.getElementById("table").getAttribute("data-options")
      );
      window.location.href =
        "./party_member_informationAdd.html?action=Modify&nodeKey=" +
        row[primary_key];
    },
    handleEdit1(row) {
      let { primary_key } = JSON.parse(
        document.getElementById("table").getAttribute("data-options")
      );
      window.location.href = "./party_member_informationAdd.html?action=Modify&nodeKey=" + row[primary_key] + "&type=1";
    },
    handleEdit2(row) {
      let { primary_key } = JSON.parse(
        document.getElementById("table").getAttribute("data-options")
      );
      window.location.href = "./party_member_informationAdd.html?action=Modify&nodeKey=" + row[primary_key] + "&type=2";
    },
    handleEdit3(row) {
      let { primary_key } = JSON.parse(
        document.getElementById("table").getAttribute("data-options")
      );
      window.location.href = "./party_member_informationAdd.html?action=Modify&nodeKey=" + row[primary_key] + "&type=3";
    },
    handleEdit4(row) {
      let { primary_key } = JSON.parse(
        document.getElementById("table").getAttribute("data-options")
      );
      window.location.href = "./party_member_informationAdd.html?action=Modify&nodeKey=" + row[primary_key] + "&type=4";
    },
    handleShow(row) {
      let { primary_key } = JSON.parse(document.getElementById("table").getAttribute("data-options"));
      window.location.href = './show.html?action=Modify&nodeKey=' + row[primary_key];
    },
  },
};

const { createApp } = Vue;
const app = createApp(App);
app.component('yl-tenure-tree', ylTenureTree);
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}
const ElMessage = ElementPlus.ElMessage;
app.use(ElementPlus, { locale: zhCn });
app.mount("#app");
